package com.authenticateCenter.domain.entity;

import java.io.Serializable;
import java.util.List;

import cn.hutool.extra.spring.SpringUtil;
import com.authenticateCenter.domain.Checker;
import com.authenticateCenter.domain.entity.util.EntityUtil;
import com.authenticateCenter.mapper.AuthorityMapper;
import com.authenticateCenter.service.IAuthorityModuleService;
import com.authenticateCenter.util.MybatisUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.*;

/**
 * <p>
 * 
 * </p>
 *
 * @author 大忽悠
 * @since 2022年10月08日
 */
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Authority implements Serializable, Checker<Authority> {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String pattern;

    private String description;

    private Integer enabled;

    private Integer moduleId;

    public static void existCheck(List<Integer> authorityIdList, AuthorityMapper authorityMapper) {
        boolean exists = authorityMapper.exists(new QueryWrapper<Authority>()
                .in("id", authorityIdList));
        if(!exists){
            throw new IllegalArgumentException("权限列表集合中,存在错误的权限id: "+authorityIdList);
        }
    }

    @Override
    public void insertCheck(IService<Authority> iService) {
        MybatisUtil.repeatCheck(iService,"pattern",pattern,"已经存在pattern为: "+pattern+"的资源路径了");
        EntityUtil.enabledCheck(this);
        //当前资源关联的资源模块如果设置了,那么必须要存在才可以
        if(moduleId!=null){
          MybatisUtil.resourceMustExist(SpringUtil.getBean(IAuthorityModuleService.class),"id",moduleId,"当前资源关联的资源模块不存在");
        }
    }

    public boolean enableIf() {
        Integer moduleId = getModuleId();
        //属于默认模块
        if(moduleId==-1){
            return getEnabled()==1;
        }
        //模块没有被禁用,并且资源本身也没有被禁用
        return SpringUtil.getBean(IAuthorityModuleService.class).getById(moduleId).getEnabled()==1 && getEnabled()==1;
    }
}
